package action.user;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.struts2.ServletActionContext;

import service.UserService;
import bean.User;

import com.opensymphony.xwork2.ActionSupport;


public class AddUserAction extends ActionSupport {
	private File file;
	private String fileContentType;
	private String fileFileName;
	private User user;
	private UserService userService;

	@Override
	public String execute() throws Exception {
		String filename;
		if(file==null){
			filename="image/default.gif";
			user.setImage(filename);
		}else{
			filename=user.getUsername()+fileFileName.substring(fileFileName.lastIndexOf('.'));
			user.setImage("image/users/"+filename);
		}
		if(userService.register(user)){
			if(file!=null){
			byte[] buffer=new byte[1024];
			InputStream in=new FileInputStream(file);
			OutputStream out=new FileOutputStream(new File(ServletActionContext.getServletContext().getRealPath("/image/users")+"/"+filename));
			int length=in.read(buffer);
			while(length>0){
				out.write(buffer);
				length=in.read(buffer);
			}
			in.close();
			out.flush();
			out.close();
			}
			User u=userService.login(user);
			ServletActionContext.getContext().getSession().put("user", u);
			return SUCCESS;
		}
		else{
			return INPUT;
		}
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	
	
}
